package array;

/**
 * @Author Yi Jun jie
 * @Date 2021/3/1 15:56
 * 867. 转置矩阵
 */
public class LeetCode867 {
    public static void main(String[] args) {
        //int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}};
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
        System.out.println("输入的数据：");
        observe(matrix);
        System.out.println("输出的数据：");
        observe(new Solution867().transposePlus(matrix));
    }

    //遍历数组用于显示
    public static void observe(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

class Solution867 {
    public int[][] transpose(int[][] matrix) {
        int lx = matrix[0].length, ly = matrix.length;
        int x, y;
        int[][] array = new int[lx][ly];//先写出数组的大小
        for (y = 0; y < ly; y++) {
            for (x = 0; x < lx; x++) {
                array[x][y] = matrix[y][x];
            }
        }
        return array;
    }

    //网上优解-----------------------------------------
    public int[][] transposePlus(int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        int res[][] = new int[col][row];
        for (int i = 0; i < col; i++) {
            for (int j = 0; j < row; j++) {
                res[i][j] = matrix[j][i];
            }
        }
        return res;
    }
}


